<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Edit Work Group</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		input {
			font-size: 20px;
		}
		select {
			font-size: 20px;
		}
		a {
	      text-decoration:none;
	   	}
	</style>
</head>
<body>

<%
	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
		
	int workgroupId = Integer.parseInt(request.getParameter("workgroupId"));
	int departmentId = Integer.parseInt(request.getParameter("departmentId"));
	String workgroupOld = new String(request.getParameter("workgroupName").getBytes("ISO8859_1"),"UTF-8");
	String departmentOld = new String(request.getParameter("departmentName").getBytes("ISO8859_1"),"UTF-8");
			
	System.out.println("EDIT workgroupId "+workgroupId);////////try////////
	System.out.println("EDIT departmentId "+departmentId);////////try////////
	System.out.println("EDIT workgroupOld "+workgroupOld);////////try////////
	System.out.println("EDIT departmentOld "+departmentOld);////////try////////


	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find department in database */
	List<Department> department = new ArrayList<Department>();
	
	try {			   
		ResultSet rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
				+ " FROM department " + " ORDER BY department_id");
		
		while(rs_department.next()) {
			Department dep = new Department();
			
			dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
			dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
			
			department.add(dep);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
        		
        		<div id="main-content-ac">
      		
						<div class="imageFrame">แก้ไขหน่วยงาน</div>
						
						<br/><br/><br/><br/><br/><br/>
						<center>

							<table width="600"  border="0">
						    	<form id="form1" name="form1" method="post" action="">	
						    		<input type="hidden" name="workgroupId" id="workgroupId" value="<%=workgroupId %>" />
						    								           
						            <tr style="font-size:24px">
						            	<td height="50" width="250">
						                	<font size="5"><strong>ภาควิชา</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						              	
						              	<input type="hidden" name="departmentId" id="departmentId" value="<%=departmentId %>" />
						              	<input type="hidden" name="departmentName" id="departmentName" value="<%=departmentOld %>" />
						              	<td height="50">
						                	<select name="department" id="department">
							                	<option value="<%=departmentId %>"><%=departmentOld %></option>
<%
												for(Department dept : department) {
													if(departmentId == dept.getDepartmentId()) {
														
													}
													else {
%>
														<option value="<%=dept.getDepartmentId()%>" id="<%=dept.getDepartmentId()%>"><%=dept.getDepartmentNameTH()%></option>	
<%												
													}
												}
%>
							                </select>
							                
							        	</td>
						            </tr>
						             
						            <tr style="font-size:24px">
						            	<input type="hidden" name="workgroupName" id="workgroupName" value="<%=workgroupOld %>" />
						            	<td height="50">
						                	<font size="5"><strong>หน่วยงาน</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td height="50">
						                	<input type="text" name="workgroup" id="workgroup" value="<%=workgroupOld %>" required/>
						                </td>
						            </tr>
						            
						            <tr>
						            	<td colspan="2">
						            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
						            	</td>
						            </tr>
						
						             <tr style="font-size:24px">
						            	<td height="50">
						                	<center><input type="submit" value="save" name="save" class="buttonStyle" /></center>
						                </td>
						           </form>
						                <td height="50">
						                	<a href="admin_workgroup.jsp"><button class="buttonStyle">cancel</button></a>
						                </td>
						            </tr>
						       </table> 
						</center>
        		
        									
						<br><br><br>

					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
	</div>

<%
				String checkButton = request.getParameter("save");
				System.out.println("checkButton : "+checkButton);////////////////////try///////////////////
				// check save button is pressed
				if("save".equals(checkButton)) {
					// get value from tag
					int departmentIdNew = Integer.parseInt(request.getParameter("department"));
					String workgroupNew =  new String(request.getParameter("workgroup").getBytes("ISO8859_1"),"UTF-8");
					
					System.out.println("DEP ID NEW : "+departmentIdNew);///////////try////////////
					System.out.println("WRK ID NEW : "+workgroupNew);///////////try////////////
					// check special character
				   	Pattern regex = Pattern.compile("[$&+,:;=?@#^*<>)(|!%]");
				   	Matcher matcherworkgroupName = regex.matcher(workgroupNew);
				   	if (matcherworkgroupName.find()){
					%>
									<script language="javascript"> alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");	</script>
					<%}else{
					
						if(!(departmentIdNew == departmentId) || !workgroupNew.equals(workgroupOld)) {
							try {		
								// check work group name exist
								ResultSet rs = connect.createStatement().executeQuery("SELECT workgroup_name "
															+ " FROM workgroup "
															+ " WHERE workgroup_name='"+workgroupNew+"' AND department_id="+departmentId);
								
								rs.last();
								if(rs.getRow() == 1) {
				%>
									<script language="javascript"> alert("หน่วยงานนี้มีอยู่ในระบบแล้ว กรุณากรอกใหม่อีกครั้งค่ะ");	</script>
				<%								
								}
								else {
									String sql = "UPDATE `workgroup` SET `department_id`=" + departmentIdNew + " "
											+ " ,`workgroup_name`='" + workgroupNew +"' "
											+ " ,`workgroup_name`='" + workgroupNew +"' "
									+ " WHERE workgroup_id="+workgroupId;
									connect.createStatement().executeUpdate(sql);
									
									/* Log file */
									String log = "admin edit workgroup";
									Log.writeAdminFile(log);
									Log.writeAdminFile(sql);
								
							
		%>
								<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
								<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_workgroup.jsp">
								
		<%
								}
							} catch (SQLException e) {
								e.printStackTrace();
				%>
								<script language="javascript"> alert("มีข้อผิดพลาดเกิดขึ้น กรุณาลองใหม่อีกครั้งค่ะ");	</script>
				<%
							}	
						}
						else {
	%>
							<script language="javascript"> alert("ข้อมูลไม่มีการเปลี่ยนแปลง กรุณาตรวจสอบอีกครั้งค่ะ");	</script>						
	<%
						}
					}
				}
				
				connect.close();
%>

</body>
</html>